from utils import get_exchange_info, df_into_db
import pandas as pd
import json

def main():
    exchange_info = get_exchange_info()
    assets = exchange_info['assets']
    df_into_db(pd.DataFrame(assets), "assets")
    get_symbols(exchange_info)
    get_filters(exchange_info)


def get_symbols(exchange_info):
    symbols = exchange_info['symbols']
    symbols_df = pd.DataFrame(symbols)
    for column in ['filters', 'underlyingSubType', 'orderTypes', 'timeInForce', 'permissionSets']:
        symbols_df[column] = symbols_df[column].apply(lambda x: json.dumps(x))
    df_into_db(symbols_df, "symbols")


def get_filters(exchange_info):
    symbols = exchange_info['symbols']
    result_map_list = []
    filter_columns = ['PRICE_FILTER', 'LOT_SIZE', 'MARKET_LOT_SIZE', 'MAX_NUM_ORDERS', 'MAX_NUM_ALGO_ORDERS', 'MIN_NOTIONAL',
     'PERCENT_PRICE', 'POSITION_RISK_CONTROL']
    for symbol in symbols:
        result_map = {}
        result_map['symbol'] = symbol['symbol']
        filters = symbol['filters']
        for filter in filters:
            assert filter['filterType'] in filter_columns
            filter_type = filter.pop('filterType')
            result_map[filter_type] = filter
        for filter_column in filter_columns:
            if filter_column not in result_map:
                result_map[filter_column] = {}
        result_map_list.append(result_map)
    result_df = pd.DataFrame(result_map_list)
    for column in filter_columns:
        result_df[column] = result_df[column].apply(lambda x: json.dumps(x))
    df_into_db(result_df, "symbol_filters")


if __name__ == '__main__':
    main()